<script setup>
import doctorSchedulesApi from '@/api/doctorSchedulesApi';
import {reactive, ref} from 'vue';
import departmentApi from "@/api/departmentApi";
import {ElMessage, ElMessageBox} from 'element-plus'
import service from '@/api';
import doctorsApi from '@/api/doctorsApi';
import reserveApi from '@/api/reserveApi';

import ReserveSign from './ReserveSign.vue'
import {Refresh, Search} from "@element-plus/icons-vue";

const doctors = ref([]);
const departments = ref([]);
const doctorSchedules = ref([]);
// 添加日期范围临时变量
const dateRangeValue = ref(null);
// 分页信息
const pageInfo = reactive({
  page: 1,
  limit: 10,
  total: 0,
  name: '',
  doctorId: '',
})

// 获取活动表;
loadDoctorSchedules();
loadDoctor();
loadDepartments();
//查询科室列表
function loadDepartments() {
  departmentApi.getAll().then(result => {
    departments.value = result.data;
  });
}
// 页码和页面大小更新
function loadDoctorSchedules() {
  doctorSchedulesApi.search(pageInfo).then(result => {
    doctorSchedules.value = result.data.records;
    pageInfo.total = result.data.total;

    // 获取每个排班的已预约人数
    doctorSchedules.value.forEach(schedule => {
      doctorSchedulesApi.getReservedCount(schedule.id).then(res => {
        if (res.code == "200") {
          // console.log("111"+res.data)
          schedule.reservedCount = res.data;
        }
      });
    });
  });
}


// 页码和页面大小更新
function loadDoctor() {
  doctorsApi.getAll().then(result => {
    doctors.value = result.data;
  });
}

// 添加的相关操作
const addVisible = ref(false);

const addDoctorSchedule = ref({
  maxCount: 20,
  length: 90,
});

function showAdd() {
  addVisible.value = true;    // 显示添加窗口
}

function handleAdd() {
  doctorSchedulesApi.add(addDoctorSchedule.value).then(result => {
    if (result.code == 200) {
      ElMessage({message: '活动创建成功！', type: 'success'})
      addVisible.value = false;
      addDoctorSchedule.value = {};
    } else {
      ElMessage.error(result.data);
    }
    // 刷新表格数据
    loadDoctorSchedules();
  });
}

// 编辑的操作
const editVisible = ref(false);
const editDoctorSchedules = ref({
  id: '',
  name: '',
});

// 编辑
function showEdit(row) {
  editVisible.value = true;
  editDoctorSchedules.value = JSON.parse(JSON.stringify(row));// 深拷贝

  console.log(row);
}

function handleEdit() {
  doctorSchedulesApi.edit(editDoctorSchedules.value).then(result => {
    if (result.code == 200) {
      ElMessage({message: '编辑活动成功！', type: 'success'})
      editVisible.value = false;
      editDoctorSchedules.value = {};
    } else {
      ElMessage.error(result.data);
    }
    // 刷新表格数据
    loadDoctorSchedules();
  });
}

function handleRemove(doctorSchedules) {
  ElMessageBox.confirm(
      '亲，确定要取消当前活动么?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '我还要想想',
        type: 'warning',
      }
  ).then(() => {
    // 确定
    doctorSchedulesApi.remove(doctorSchedules.id).then(result => {
      if (result.code == 200) {
        ElMessage({message: '移除活动成功！', type: 'success'})
      } else {
        ElMessage.error(result.data);
      }
      // 刷新表格数据
      loadDoctorSchedules();
    });
  });

}

function onSearch() {
  pageInfo.page = 1;
  loadDoctorSchedules();
}

// 预约相关
const reserveVisible = ref(false);

function showReserve(row) {
  reserveVisible.value = true;
  editDoctorSchedules.value = row;
}
// 解析状态显示
function fmtStatus(row, column, cellValue, index) {
  // 1: 可预约, 2: 已约满, 3: 活动取消 4:结束预约 5:活动结束
  const statusMap = {
    1: '可预约',
    2: '已约满',
    3: '活动取消',
    4: '结束预约',
    5: '活动结束'
  };
  return statusMap[row.status] || '未知状态';
}

// 根据状态返回不同的样式类
function getStatusClass(row) {
  // 1: 可预约, 2: 已约满, 3: 活动取消
  const statusClasses = ['status-unknown', 'status-available', 'status-full', 'status-cancelled'];
  return statusClasses[row.status] || 'status-unknown';
}

// 添加时间范围选择处理函数
function handleDateRangeChange(value) {
  if (value && value.length === 2) {
    pageInfo.dsStartTime = value[0];
    pageInfo.dsEndTime = value[1];
  } else {
    pageInfo.dsStartTime = null;
    pageInfo.dsEndTime= null;
    dateRangeValue.value = null;
  }
}
// 重置搜索条件
function resetSearch() {
  // 清空搜索条件
  pageInfo.name = '';
  pageInfo.doctorId = '';
  pageInfo.dsStartTime = null;
  pageInfo.dsEndTime = null;
  dateRangeValue.value = null;

  // 重置页码
  pageInfo.page = 1;
  loadDoctorSchedules();
}
// 父组件中定义处理函数
function handleRefreshParent() {
  // 在这里执行父组件需要的刷新逻辑
  // console.log('子组件刷新完成，父组件也开始刷新');
  // 重新加载父组件数据
  loadDoctorSchedules();
}


const rules=ref({
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  doctorId: [
    { required: true, message: '请选择义诊医生', trigger: 'change' }
  ],
  departmentId: [
    { required: true, message: '请选择科室', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  totalSlots: [
    { required: true, message: '请输入最大人数', trigger: 'blur' }
  ],
  longTime: [
    { required: true, message: '请输入持续时长', trigger: 'blur' }
  ]
})
</script>

<template>
  <div class="content">
    <el-form :model="pageInfo" :inline="true">
      <el-form-item label="活动名称" :label-width="80">
        <el-input v-model="pageInfo.name" clearable placeholder="请输入活动名称"/>
      </el-form-item>
      <el-form-item label="主治医生" :label-width="80">
        <el-select
            v-model="pageInfo.doctorId"
            value-key="id"
            placeholder="请选择医生"
            style="width: 240px"
            clearable
        >
          <el-option
              v-for="item in doctors"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- 添加时间范围选择器 -->
      <el-form-item label="活动时间" :label-width="80">
        <el-date-picker
            v-model="dateRangeValue"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
            clearable
            @change="handleDateRangeChange"
        />
      </el-form-item>
      <el-form-item>

        <el-button type="primary" @click="onSearch">
          <el-icon><Search /></el-icon>
          <span>搜索</span>
        </el-button>


        <el-button @click="resetSearch" style="margin-left: 10px;">
          <el-icon><Refresh /></el-icon>
          <span>重置</span>
        </el-button>
      </el-form-item>

    </el-form>

    <div class="bar">
      <el-button type="success" @click="showAdd()">创建活动</el-button>
    </div>
    <el-table :data="doctorSchedules" :stripe="true" :border="true" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" fixed/>
      <el-table-column prop="name" label="义诊活动名" width="150" fixed/>
      <el-table-column prop="doctorName" label="医生名" width="130" fixed/>
      <el-table-column prop="departmentName" label="科室名"/>
      <el-table-column prop="startTime" label="开始时间" width="180"/>
      <el-table-column prop="longTime" label="持续时间" width="100"/>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
                    <span :class="['status-badge', getStatusClass(scope.row)]">
                        {{ fmtStatus(scope.row, null, null, null) }}
                    </span>
        </template>
      </el-table-column>
<el-table-column label="预约情况" width="150">
  <template #default="scope">
    <span>{{ scope.row.reservedCount || 0 }} / {{ scope.row.totalSlots }}</span>
  </template>
</el-table-column>
      <el-table-column label="操作" width="300px" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary"
                     @click="showReserve(scope.row)">报名患者
          </el-button>
          <el-button size="small" type="success"
                     @click="showEdit(scope.row)">编辑
          </el-button>
          <el-button size="small" type="danger"
                     @click="handleRemove(scope.row)">取消活动
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
                   :total="pageInfo.total" :page-sizes="[10, 20, 50, 100]" :background="true"
                   layout="total, sizes, prev, pager, next, jumper" @change="loadDoctorSchedules"/>
  </div>

  <!-- 添加的弹窗 -->
  <el-dialog v-model="addVisible" title="创建义诊活动" width="750">
    <el-form :model="addDoctorSchedule" :rules="rules">

      <el-form-item label="义诊活动名" :label-width="100" prop="name">
        <el-input v-model="addDoctorSchedule.name" placeholder="请输入活动名字"/>
      </el-form-item>
      <el-form-item label="主治医师" :label-width="100" >
        <el-select
            v-model="addDoctorSchedule.doctorId"
            value-key="id"
            placeholder="请选择主治医生"
            style="width: 240px"
        >
          <el-option
              v-for="item in doctors"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择科室" :label-width="100" >
        <el-col :span="10">
          <el-select
              v-model="addDoctorSchedule.departmentId"
              value-key="id"
              placeholder="请选择科室"
              style="width: 240px"
          >
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="4" style="text-align: center;">
          <span class="text-gray-500" >最大人数</span>
        </el-col>
        <el-col :span="8">
          <el-input-number v-model="addDoctorSchedule.totalSlots" :min="10" :max="120" :step="10"
                           placeholder="最大人数"/>
        </el-col>
      </el-form-item>
      <el-form-item label="开始时间" :label-width="100" prop="startTime">
        <el-col :span="10">
          <el-date-picker
              v-model="addDoctorSchedule.startTime"
              editable
              type="datetime"
              placeholder="开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 240px"
          />
        </el-col>
        <el-col :span="4" style="text-align: center; "  >
          <span class="text-gray-500">持续时长</span>
        </el-col>
        <el-col :span="8">
          <el-input-number v-model="addDoctorSchedule.longTime" :min="10" :max="120" :step="10" placeholder="持续时长"/>
        </el-col>
        <el-col :span="2" style="text-align: center; margin-left: -60px;">
          <span class="text-gray-500">分钟</span>
        </el-col>

      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">
          创建
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑的弹窗 -->
  <el-dialog v-model="editVisible" title="修改义诊活动" width="750">
    <el-form :model="editDoctorSchedules" :rules="rules">
      <el-form-item label="义诊活动名" :label-width="100" prop="name">
        <el-input v-model="editDoctorSchedules.name" placeholder="请输入活动名字"/>
      </el-form-item>
      <el-form-item label="义诊医师" :label-width="100" >
        <el-select
            v-model="editDoctorSchedules.doctorId"
            value-key="id"
            placeholder="请选择义诊医生"
            style="width: 240px"
        >
          <el-option
              v-for="item in doctors"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择科室" :label-width="100" >
        <el-col :span="10">
          <el-select
              v-model="editDoctorSchedules.departmentId"
              value-key="id"
              placeholder="请选择科室"
              style="width: 240px"
          >
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="4" style="text-align: center;">
          <span class="text-gray-500">最大人数</span>
        </el-col>
        <el-col :span="8">
          <el-input-number v-model="editDoctorSchedules.totalSlots" :min="10" :max="120" :step="10"
                           placeholder="最大人数"/>
        </el-col>
      </el-form-item>
      <el-form-item label="开始时间" :label-width="100" prop="startTime">
        <el-col :span="10">
          <el-date-picker
              v-model="editDoctorSchedules.startTime"
              editable
              type="datetime"
              placeholder="上课时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 240px"
          />
        </el-col>
        <el-col :span="4" style="text-align: center;">
          <span class="text-gray-500">持续时长</span>
        </el-col>
        <el-col :span="8">
          <el-input-number v-model="editDoctorSchedules.longTime" :min="10" :max="120" :step="10" placeholder="持续时长"/>
        </el-col>
        <el-col :span="2" style="text-align: center; margin-left: -60px;">
          <span class="text-gray-500">分钟</span>
        </el-col>

      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">
          编辑
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="reserveVisible" title="报名患者" width="70%">
    <ReserveSign  v-model="editDoctorSchedules" @refresh-parent="handleRefreshParent" ></ReserveSign>
  </el-dialog>
</template>

<style scoped>
/* 状态标签样式 */
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  white-space: nowrap;
}

/* 未知状态 - 灰色 */
.status-unknown {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #d3d4d6;
}

/* 可预约状态 - 绿色 */
.status-available {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

/* 已约满状态 - 橙色 */
.status-full {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #f5dab1;
}

/* 活动取消状态 - 红色 */
.status-cancelled {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}
</style>